package com.qumitech.visualnovel.controller.rest.account;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import com.qumitech.visualnovel.config.shiro.MyShiroRealm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;
import com.qumitech.visualnovel.model.common.BaseResponse;
import com.qumitech.visualnovel.model.dao.console.SysRole;
import com.qumitech.visualnovel.model.dao.console.UserInfo;
import com.qumitech.visualnovel.service.account.SysRolePermissionService;
import com.qumitech.visualnovel.service.account.SysRoleService;
import com.qumitech.visualnovel.service.account.SysUserRoleService;
import java.util.List;

@RestController
@RequestMapping("/api/role")
@Api(value = "系统账户角色管理", description = "系统账户角色管理")
public class SysRoleController {

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SysRolePermissionService sysRolePermissionService;

    @Autowired
    SysUserRoleService sysUserRoleService;

    @ApiOperation(value = "系统角色列表", notes = "系统角色列表")
    @RequestMapping(value = "/roleList", method = RequestMethod.GET)
    public JSONObject SysRoleList(
            @RequestParam(value="offset", required=false, defaultValue="0") int offset,
            @RequestParam(value="limit", required=false, defaultValue="20") int limit,
            @RequestParam(value="orderType", required=false, defaultValue="DESC") String orderType,
            @RequestParam(value="orderBy", required=false, defaultValue="target_date") String orderBy){
        JSONObject data = new JSONObject();
        int count = sysRoleService.getSysRoleCount();
        data.put("count", count);
        JSONArray dataItems = new JSONArray();
        List<SysRole> sysRoleList = sysRoleService.getSysRoleList(offset,limit,orderBy,orderType);
        for(SysRole sysRole: sysRoleList)
        {
            dataItems.add(sysRole.toJsonObject());
        }
        data.put("items", dataItems);
        BaseResponse results = new BaseResponse(data);
        return results;
    }

    @ApiOperation(value = "添加系统角色", notes = "添加系统角色")
    @RequestMapping(value = "/roleAdd", method = RequestMethod.POST)
    public JSONObject SysRoleAdd(@RequestBody JSONObject params){
        JSONObject data = new JSONObject();
        String roleName = params.getString("roleName");
        String description = params.getString("description");
        JSONArray permissionIdArray = params.getJSONArray("excludeHalfCheckedPermissionIds");
        BaseResponse results = new BaseResponse(data);
        try {
            sysRoleService.insertSysRole(roleName, description, true);
            SysRole sysRole = sysRoleService.getSysRoleByRoleName(roleName);
            sysRolePermissionService.setSysRolePermission(sysRole.getId(), permissionIdArray); //添加角色和权限绑定关系
            //添加角色之后刷新权限
            RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
            MyShiroRealm authRealm = (MyShiroRealm)rsm.getRealms().iterator().next();
            authRealm.clearAuthz();
            //如果当前的用户处于修改的角色里面，就要更新当前用户的权限
            Subject subject = SecurityUtils.getSubject();
            UserInfo activeUser = (UserInfo) subject.getPrincipal();
            List<UserInfo> userInfoList = sysUserRoleService.getUsersByRoleId(sysRole.getId());
            if(userInfoList != null) {
                for (UserInfo userInfo : userInfoList) {
                    //找到当前用户，就更新角色
                    if (activeUser.getUid() == userInfo.getUid()) {
                        activeUser.setSysRoleList(userInfo.getSysRoleList());
                    }
                }
            }
        }catch (DuplicateKeyException e)
        {
            results.put("msg", "该角色名已存在");
            results.put("code", -1);
        }
        catch (Exception e)
        {
            results.put("msg", e.toString());
            results.put("code", -1);
        }
        return results;
    }


    @ApiOperation(value = "更新系统角色", notes = "更新系统角色")
    @RequestMapping(value = "/roleUpdate", method = RequestMethod.POST)
    public JSONObject SysRoleUpdate(@RequestBody JSONObject params){
        JSONObject data = new JSONObject();
        int roleId = params.getInteger("id");
        String description = params.getString("description");
        JSONArray permissionIdArray = params.getJSONArray("excludeHalfCheckedPermissionIds");
        BaseResponse results = new BaseResponse(data);
        try
        {
            SysRole sysRole = sysRoleService.getSysRoleById(roleId);
            sysRole.setDescriptiion(description);
            sysRoleService.UpdateBySysRole(sysRole);
            sysRolePermissionService.setSysRolePermission(sysRole.getId(), permissionIdArray);//更新绑定关系
            //修改角色之后刷新权限
            RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
            MyShiroRealm authRealm = (MyShiroRealm)rsm.getRealms().iterator().next();
            authRealm.clearAuthz();
            //如果当前的用户处于修改的角色里面，就要更新当前用户的权限
            Subject subject = SecurityUtils.getSubject();
            UserInfo activeUser = (UserInfo) subject.getPrincipal();
            List<UserInfo> userInfoList = sysUserRoleService.getUsersByRoleId(sysRole.getId());
            if(userInfoList != null) {
                for (UserInfo userInfo : userInfoList) {
                    //找到当前用户，就更新角色
                    if (activeUser.getUid() == userInfo.getUid()) {
                        activeUser.setSysRoleList(userInfo.getSysRoleList());
                    }
                }
            }
        }catch (Exception e)
        {
            results.put("msg", e.toString());
            results.put("code", -1);
            return results;
        }
        return results;
    }

    @ApiOperation(value = "删除系统角色", notes = "删除系统角色")
    @RequestMapping(value = "/roleDel", method = RequestMethod.POST)
    public JSONObject userDel(@RequestBody JSONObject params){
        JSONObject data = new JSONObject();
        int roleId = params.getInteger("id");
        BaseResponse results = new BaseResponse(data);
        try
        {
            List<UserInfo> sysRoleList = sysUserRoleService.getUsersByRoleId(roleId);
            if(sysRoleList.size() > 0) //           如果找到用户，就不允许删除这个角色
            {
                results.put("msg", "该角色存在关联的用户，不允许删除");
                results.put("code", -1);
            }
            else
            {
                sysRoleService.deleteByPrimaryKey(roleId);
            }
        }catch (Exception e)
        {
            results.put("msg", e.toString());
            results.put("code", -1);
        }
        return results;
    }


    @ApiOperation(value = "系统角色选项", notes = "系统角色选项")
    @RequestMapping(value = "/roleOptions", method = RequestMethod.GET)
    public JSONObject RoleListConfig(){
        JSONObject data = new JSONObject();
        int count = sysRoleService.getSysRoleCount();
        JSONArray dataItems = new JSONArray();
        List<SysRole> sysRoleList = sysRoleService.getSysRoleList(0,count,null,null);
        for(SysRole sysRole: sysRoleList)
        {
            JSONObject sysRoleJson = new JSONObject();
            sysRoleJson.put("id", sysRole.getId());
            sysRoleJson.put("text", sysRole.getRoleName());
            dataItems.add(sysRoleJson);
        }
        data.put("items", dataItems);
        BaseResponse results = new BaseResponse(data);
        return results;
    }
}
